package com.example.demo.Service;

import com.example.demo.Entity.Interested;
import java.util.Optional;
import com.example.demo.Entity.User;
import com.example.demo.Entity.Work;
import com.example.demo.Repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.Entity.Item;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private WorkRepository workRepository;

    @Autowired
    private InterestedRepository interestedRepository;
    @Autowired
    private ItemRepository itemRepository;

    public User getUserInfo(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }

    public List<Work> getUserWorks(Long userId) {
        return workRepository.findByUser_Id(userId);
    }

    public List<String> getUserLikedImageUrls(Long userId) {
        List<Interested> interests = interestedRepository.findByUserId(userId);
        return interests.stream()
                .map(Interested::getItemId)
                .map(itemRepository::findById)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .map(Item::getImageUrl)
                .collect(Collectors.toList());
    }
    /**
     * 根据用户名和密码查找用户。
     * @param username 用户名
     * @param password 密码
     * @return 如果找到匹配的用户，则返回该用户；否则返回null。
     */
    public User findByUsernameAndPassword(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }

    public User updateUser(Long id, User updatedUser) {
        return userRepository.findById(id).map(user -> {
            // 只更新非空字段
            if (updatedUser.getUsername() != null && !updatedUser.getUsername().isEmpty()) {
                user.setUsername(updatedUser.getUsername());
            }
            if (updatedUser.getPassword() != null && !updatedUser.getPassword().isEmpty()) {
                user.setPassword(updatedUser.getPassword());
            }
            if (updatedUser.getSignature() != null && !updatedUser.getSignature().isEmpty()) {
                user.setSignature(updatedUser.getSignature());
            }
            // 如果提供了新的 imageUrl，则更新
            if (updatedUser.getImageUrl() != null && !updatedUser.getImageUrl().isEmpty()) {
                user.setImageUrl(updatedUser.getImageUrl());
            }
            return userRepository.save(user);
        }).orElseThrow(() -> new RuntimeException("User not found with id " + id));
    }
}